﻿import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../../common/styles/theme_manager.dart';
import '../../../core/models/heart_rate_api_data.dart';
import '../../../widgets/fixed_header_with_tabs.dart';
import 'dart:ui' as ui;
import 'heart_rate_logic.dart';

/// 心率图表绘制器
class HeartRateChartPainter extends CustomPainter {
  final List<int> data;
  final int selectedIndex;
  final double? dragLineX;
  final int maxValue;
  final int minValue;

  HeartRateChartPainter({
    required this.data,
    required this.selectedIndex,
    this.dragLineX,
    required this.maxValue,
    required this.minValue,
  });

  @override
  void paint(Canvas canvas, Size size) {
    if (data.isEmpty) return;

    final paint = Paint()
      ..color = const Color(0xFFFFD700)
      ..strokeWidth = 2.0
      ..style = PaintingStyle.stroke;

    final pointPaint = Paint()
      ..color = const Color(0xFFFFD700)
      ..style = PaintingStyle.fill;

    final selectedPaint = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.fill;

    final path = Path();
    final pointWidth = size.width / data.length;
    final range = maxValue - minValue;
    final scaleY = size.height / range;

    for (int i = 0; i < data.length; i++) {
      final x = i * pointWidth + pointWidth / 2;
      final y = size.height - (data[i] - minValue) * scaleY;

      if (i == 0) {
        path.moveTo(x, y);
      } else {
        path.lineTo(x, y);
      }

      // 绘制数据点
      if (i == selectedIndex) {
        canvas.drawCircle(Offset(x, y), 4, selectedPaint);
      } else {
        canvas.drawCircle(Offset(x, y), 3, pointPaint);
      }
    }

    canvas.drawPath(path, paint);

    // 绘制拖动线
    if (dragLineX != null && dragLineX! > 0) {
      final linePaint = Paint()
        ..color = Colors.red.withOpacity(0.5)
        ..strokeWidth = 1.0;
      canvas.drawLine(
        Offset(dragLineX!, 0),
        Offset(dragLineX!, size.height),
        linePaint,
      );
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

/// 心率散点图绘制器
class HeartRateScatterPainter extends CustomPainter {
  final List<int> heartRateList;
  final int timeInterval;
  final int selectedIndex;
  final double? dragLineX;

  HeartRateScatterPainter({
    required this.heartRateList,
    required this.timeInterval,
    required this.selectedIndex,
    this.dragLineX,
  });

  @override
  void paint(Canvas canvas, Size size) {
    if (heartRateList.isEmpty) return;

    final pointPaint = Paint()
      ..color = const Color(0xFFFFD700)
      ..style = PaintingStyle.fill;

    final selectedPaint = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.fill;

    // 过滤有效的心率数据（排除0值）
    final validData = <MapEntry<int, int>>[];
    for (int i = 0; i < heartRateList.length; i++) {
      if (heartRateList[i] > 0) {
        validData.add(MapEntry(i, heartRateList[i]));
      }
    }

    if (validData.isEmpty) return;

    // 计算心率轴的范围
    final minHeartRate =
        validData.map((e) => e.value).reduce((a, b) => a < b ? a : b);
    final maxHeartRate =
        validData.map((e) => e.value).reduce((a, b) => a > b ? a : b);

    // 设置心率轴的范围，确保有足够的显示空间
    final heartRateRange = maxHeartRate - minHeartRate;
    final displayMinHeartRate = (minHeartRate - heartRateRange * 0.1).round();
    final displayMaxHeartRate = (maxHeartRate + heartRateRange * 0.1).round();

    // 计算缩放比例 - 时间轴按24小时计算
    final scaleX = size.width / 24; // 24小时
    final scaleY = size.height / (displayMaxHeartRate - displayMinHeartRate);

    // 绘制散点
    for (final entry in validData) {
      final index = entry.key;
      final heartRate = entry.value;

      // 计算时间（小时）
      final hour = (index * timeInterval) / 60.0;
      final x = hour * scaleX;
      final y = size.height - (heartRate - displayMinHeartRate) * scaleY;

      // 根据是否被选中使用不同的画笔
      final paint = (index == selectedIndex) ? selectedPaint : pointPaint;
      final radius = (index == selectedIndex) ? 4.0 : 3.0;

      canvas.drawCircle(Offset(x, y), radius, paint);
    }

    // 绘制拖动线
    if (dragLineX != null && dragLineX! > 0) {
      final linePaint = Paint()
        ..color = Colors.red.withOpacity(0.5)
        ..strokeWidth = 1.0;
      canvas.drawLine(
        Offset(dragLineX!, 0),
        Offset(dragLineX!, size.height),
        linePaint,
      );
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

/// 心率折线图绘制器（基于API数据）
class HeartRateLineChartPainter extends CustomPainter {
  final List<HeartRateInfo> data;
  final int selectedIndex;
  final double? dragLineX;
  final int maxValue;
  final int minValue;

  HeartRateLineChartPainter({
    required this.data,
    required this.selectedIndex,
    this.dragLineX,
    required this.maxValue,
    required this.minValue,
  });

  @override
  void paint(Canvas canvas, Size size) {
    if (data.isEmpty) return;

    // 过滤有效数据（value > 0）
    final validData = data.where((info) => info.value > 0).toList();
    if (validData.isEmpty) return;

    // 橙色折线画笔
    final linePaint = Paint()
      ..color = const Color(0xFFFF8C00)
      ..strokeWidth = 2.0
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round;

    // 数据点画笔
    final pointPaint = Paint()
      ..color = const Color(0xFFFF8C00)
      ..style = PaintingStyle.fill;

    // 选中点画笔
    final selectedPaint = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.fill;

    // 计算心率范围
    final range = maxValue - minValue;
    final displayMinValue = minValue - (range * 0.1).round();
    final displayMaxValue = maxValue + (range * 0.1).round();
    final displayRange = displayMaxValue - displayMinValue;

    // 计算缩放比例
    final scaleY = size.height / displayRange;

    // 创建曲线路径
    final linePath = Path();
    // 创建填充区域路径
    final fillPath = Path();
    double? lastX;

    // 收集所有有效数据点
    final List<Offset> points = [];
    for (int i = 0; i < data.length; i++) {
      final info = data[i];
      if (info.value <= 0) continue;

      // 解析时间（格式：HH:mm）
      final timeParts = info.code.split(':');
      final hour = int.parse(timeParts[0]);
      final minute = int.parse(timeParts[1]);
      final timeInHours = hour + minute / 60.0;

      // 计算坐标
      final x = (timeInHours / 24.0) * size.width;
      final y = size.height - (info.value - displayMinValue) * scaleY;
      
      points.add(Offset(x, y));
    }

    // 绘制平滑曲线
    if (points.isNotEmpty) {
      linePath.moveTo(points[0].dx, points[0].dy);
      fillPath.moveTo(points[0].dx, size.height);
      fillPath.lineTo(points[0].dx, points[0].dy);

      for (int i = 0; i < points.length - 1; i++) {
        final p0 = i > 0 ? points[i - 1] : points[i];
        final p1 = points[i];
        final p2 = points[i + 1];
        final p3 = i < points.length - 2 ? points[i + 2] : p2;

        // 计算控制点
        final cp1x = p1.dx + (p2.dx - p0.dx) / 6;
        final cp1y = p1.dy + (p2.dy - p0.dy) / 6;
        final cp2x = p2.dx - (p3.dx - p1.dx) / 6;
        final cp2y = p2.dy - (p3.dy - p1.dy) / 6;

        linePath.cubicTo(cp1x, cp1y, cp2x, cp2y, p2.dx, p2.dy);
        fillPath.cubicTo(cp1x, cp1y, cp2x, cp2y, p2.dx, p2.dy);
      }

      lastX = points.last.dx;
    }

    // 完成填充路径
    if (lastX != null) {
      fillPath.lineTo(lastX, size.height);
      fillPath.close();

      // 绘制渐变填充
      final fillPaint = Paint()
        ..shader = ui.Gradient.linear(
          Offset(0, 0),
          Offset(0, size.height),
          [
            const Color(0xFFFF8C00).withOpacity(0.4),
            const Color(0xFFFF8C00).withOpacity(0.2),
            const Color(0xFFFF8C00).withOpacity(0.1),
          ],
          [0.0, 0.5, 1.0],
        )
        ..style = PaintingStyle.fill;

      canvas.drawPath(fillPath, fillPaint);
    }

    // 绘制折线
    canvas.drawPath(linePath, linePaint);

    // 绘制拖动线
    final dragX = dragLineX;
    if (dragX != null && dragX > 0) {
      final dragLinePaint = Paint()
        ..color = Colors.red.withOpacity(0.5)
        ..strokeWidth = 1.0;
      canvas.drawLine(
        Offset(dragX, 0),
        Offset(dragX, size.height),
        dragLinePaint,
      );
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

/// 心率页面
/// 显示心率数据、图表和心率区间信息
class HeartRateView extends GetView<HeartRateLogic> {
  const HeartRateView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Column(
          children: [
            // 固定的头部（标题 + 日周月切换）
            Obx(() => FixedHeaderWithTabs(
                  title: '心率',
                  selectedIndex: _getSelectedIndex(),
                  onTabChanged: (index) {
                    switch (index) {
                      case 0:
                        controller.setTimeRange(TimeRange.day);
                        break;
                      case 1:
                        controller.setTimeRange(TimeRange.week);
                        break;
                      case 2:
                        controller.setTimeRange(TimeRange.month);
                        break;
                    }
                  },
                  actions: [
                    IconButton(
                      icon: const Icon(Icons.stacked_bar_chart,
                          color: Colors.white),
                      onPressed: () {
                        Get.toNamed('/manual_measure',
                            arguments: {'type': 'heartRate'});
                      },
                    ),
                    IconButton(
                      icon: const Icon(Icons.calendar_today,
                          color: Colors.white),
                      onPressed: controller.showCalendarPicker,
                    ),
                  ],
                )),
            // 可滚动的内容区域
            Expanded(
              child: SingleChildScrollView(
                child: Stack(
                  children: [
                    // 顶部渐变背景
                    Positioned(
                      top: 0,
                      left: 0,
                      right: 0,
                      height: 240.h,
                      child: Container(
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            begin: Alignment.topRight,
                            end: Alignment.bottomRight,
                            colors: ThemeManager.to.backgroundGradientColors,
                            stops: const [0.1, 0.3, 0.7, 1.0],
                          ),
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.all(16.w),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          SizedBox(height: 20.h),
                          _buildHeartRateDisplay(),
                          SizedBox(height: 12.h),
                          _buildDateLine(),
                          SizedBox(height: 16.h),
                          _buildHeartRateScatterChartCard(), // 显示散点图卡片
                          SizedBox(height: 16.h),
                          _buildManualMeasurementRecordsCard(), // 手动测量记录卡片（独立）
                          SizedBox(height: 16.h),
                          _buildHeartRateZonesCard(), // 心率区间卡片
                          SizedBox(height: 16.h),
                          _buildAverageSleepHeartRateCard(), // 今日平均睡眠心率卡片
                          SizedBox(height: 16.h),
                          _buildHeartRateInfoCard(), // 心率信息说明卡片
                          SizedBox(height: 40.h), // 底部留空
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 获取当前选中的索引
  int _getSelectedIndex() {
    switch (controller.currentTimeRange.value) {
      case TimeRange.day:
        return 0;
      case TimeRange.week:
        return 1;
      case TimeRange.month:
        return 2;
    }
  }



  /// 构建心率显示
  Widget _buildHeartRateDisplay() {
    return Obx(() {
      // 优先使用心率平均值API数据
      final heartRateAverageData = controller.heartRateAverageData.value;
      final apiHeartRateData = controller.apiHeartRateData.value;
      final historyHeartRateData =
          controller.ringController.historyHeartRateData;
      final heartRateData = controller.heartRateData.value;

      if (heartRateAverageData != null) {
        // 使用心率平均值API数据
        int displayHeartRate;

        if (controller.selectedTimeIndex.value != -1) {
          // 显示选中时间点的心率
          final selectedIndex = controller.selectedTimeIndex.value;
          if (selectedIndex < heartRateAverageData.automaticInfoVOS.length) {
            final selectedInfo =
                heartRateAverageData.automaticInfoVOS[selectedIndex];
            if (selectedInfo.value > 0) {
              displayHeartRate = selectedInfo.value;
            } else {
              displayHeartRate = heartRateAverageData.average;
            }
          } else {
            displayHeartRate = heartRateAverageData.average;
          }
        } else {
          // 显示平均心率
          displayHeartRate = heartRateAverageData.average;
        }

        return Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Text(
              '$displayHeartRate',
              style: TextStyle(
                fontSize: 64.sp,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
            Padding(
              padding: EdgeInsets.only(bottom: 8.h),
              child: Text(
                ' BPM',
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Colors.grey[400],
                ),
              ),
            ),
          ],
        );
      } else if (apiHeartRateData != null &&
          apiHeartRateData.heartRate != null &&
          apiHeartRateData.heartRate! > 0) {
        // 使用API心率数据
        final displayHeartRate = apiHeartRateData.heartRate!;

        return Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Text(
              '$displayHeartRate',
              style: TextStyle(
                fontSize: 64.sp,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
            Padding(
              padding: EdgeInsets.only(bottom: 8.h),
              child: Text(
                ' BPM',
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Colors.grey[400],
                ),
              ),
            ),
          ],
        );
      } else if (historyHeartRateData != null) {
        // 使用历史心率数据
        int displayHeartRate;

        if (controller.selectedTimeIndex.value != -1) {
          // 显示选中时间点的心率
          final selectedIndex = controller.selectedTimeIndex.value;
          if (selectedIndex < historyHeartRateData.heartRateList.length) {
            final selectedHeartRate =
                historyHeartRateData.heartRateList[selectedIndex];
            if (selectedHeartRate != null && selectedHeartRate > 0) {
              displayHeartRate = selectedHeartRate;
            } else {
              displayHeartRate = historyHeartRateData.averageHeartRate;
            }
          } else {
            displayHeartRate = historyHeartRateData.averageHeartRate;
          }
        } else {
          // 显示平均心率
          displayHeartRate = historyHeartRateData.averageHeartRate;
        }

        return Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Text(
              '$displayHeartRate',
              style: TextStyle(
                fontSize: 64.sp,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
            Padding(
              padding: EdgeInsets.only(bottom: 8.h),
              child: Text(
                ' BPM',
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Colors.grey[400],
                ),
              ),
            ),
          ],
        );
      } else if (heartRateData != null) {
        // 使用模拟心率数据
        int displayHeartRate = 0;

        switch (controller.currentTimeRange.value) {
          case TimeRange.day:
            if (controller.selectedTimeIndex.value != -1) {
              // 显示选中时段的心率
              final hourlyData = heartRateData.hourlyData;
              displayHeartRate =
                  (controller.selectedTimeIndex.value < hourlyData.length)
                      ? hourlyData[controller.selectedTimeIndex.value]
                      : heartRateData.heartRate;
            } else {
              // 显示平均心率
              displayHeartRate = heartRateData.heartRate;
            }
            break;

          case TimeRange.week:
            displayHeartRate = heartRateData.heartRate;
            break;

          case TimeRange.month:
            displayHeartRate = heartRateData.heartRate;
            break;
        }

        return Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Text(
              '$displayHeartRate',
              style: TextStyle(
                fontSize: 64.sp,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
            Padding(
              padding: EdgeInsets.only(bottom: 8.h),
              child: Text(
                ' BPM',
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Colors.grey[400],
                ),
              ),
            ),
          ],
        );
      } else {
        return Container(
          height: 80.h,
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                if (controller.isLoadingApiData.value) ...[
                  CircularProgressIndicator(
                    valueColor:
                        AlwaysStoppedAnimation<Color>(Colors.grey[400]!),
                    strokeWidth: 2.w,
                  ),
                  SizedBox(height: 8.h),
                  Text(
                    '正在加载数据...',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.grey[500],
                    ),
                  ),
                ] else ...[
                  Text(
                    '暂无心率数据',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.grey[500],
                    ),
                  ),
                ],
              ],
            ),
          ),
        );
      }
    });
  }

  /// 构建日期行
  Widget _buildDateLine() {
    return Obx(() {
      final dateTitle = controller.getDateTitle();
      return Text(
        dateTitle,
        style: TextStyle(fontSize: 14.sp, color: Colors.grey[400]),
      );
    });
  }

  /// 构建心率散点图卡片
  Widget _buildHeartRateScatterChartCard() {
    return _buildSectionCard(
      title: '心率图',
      child: _buildHeartRateScatterChart(),
    );
  }

  /// 构建心率散点图
  Widget _buildHeartRateScatterChart() {
    return Obx(() {
      final heartRateAverageData = controller.heartRateAverageData.value;
      final timeRange = controller.currentTimeRange.value;

      // 根据时间范围显示不同的图表
      if (timeRange == TimeRange.day) {
        return _buildDayLineChart(heartRateAverageData);
      } else {
        return _buildWeekMonthBarChart(heartRateAverageData, timeRange);
      }
    });
  }

  /// 构建日视图折线图
  Widget _buildDayLineChart(HeartRateAverageData? heartRateAverageData) {
    // 如果没有数据，显示空图表结构
    if (heartRateAverageData == null) {
      return _buildEmptyDayChart();
    }

    final automaticInfoVOS = heartRateAverageData.automaticInfoVOS;
    final validData = automaticInfoVOS.where((info) => info.value > 0).toList();

    // 如果没有有效数据，显示空图表结构
    if (validData.isEmpty) {
      return _buildEmptyDayChart();
    }

    final minHeartRate = heartRateAverageData.minValue;
    final maxHeartRate = heartRateAverageData.maxValue;

    return SizedBox(
      height: 280.h,
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: 8.w,
                height: 8.w,
                decoration: const BoxDecoration(
                  color: Color(0xFFFF8C00),
                  shape: BoxShape.circle,
                ),
              ),
              SizedBox(width: 4.w),
              Text(
                '心率数据',
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Colors.grey[400],
                ),
              ),
            ],
          ),
          SizedBox(height: 12.h),
          Expanded(
            child: Builder(
              builder: (context) => GestureDetector(
                onTapUp: (details) {
                  final RenderBox box = context.findRenderObject() as RenderBox;
                  final localPosition =
                      box.globalToLocal(details.globalPosition);
                  controller.handleChartTapUp(
                      localPosition.dx, box.size.width / 24, 24);
                },
                onPanUpdate: (details) {
                  final RenderBox box = context.findRenderObject() as RenderBox;
                  final localPosition =
                      box.globalToLocal(details.globalPosition);
                  controller.handleChartPanUpdate(
                      localPosition.dx, box.size.width / 24, 24);
                },
                onPanEnd: (_) => controller.handleChartPanEnd(),
                child: CustomPaint(
                  painter: HeartRateLineChartPainter(
                    data: automaticInfoVOS,
                    selectedIndex: controller.selectedTimeIndex.value,
                    dragLineX: controller.dragLineX.value,
                    maxValue: maxHeartRate,
                    minValue: minHeartRate,
                  ),
                  child: Container(),
                ),
              ),
            ),
          ),
          SizedBox(height: 8.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: ['00:00', '06:00', '12:00', '18:00', '24:00']
                .map((label) => Text(label,
                    style: TextStyle(fontSize: 10.sp, color: Colors.grey[400])))
                .toList(),
          ),
          SizedBox(height: 16.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              Container(
                padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 12.h),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.05),
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Text('最低${minHeartRate}BPM',
                    style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[400],
                        fontWeight: FontWeight.w500)),
              ),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 12.h),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.05),
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Text('最高${maxHeartRate}BPM',
                    style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[400],
                        fontWeight: FontWeight.w500)),
              ),
            ],
          ),
          SizedBox(height: 16.h),
          Obx(() => GestureDetector(
                onTap: controller.isMeasuring.value
                    ? null
                    : controller.startHeartRateMeasurement,
                child: Container(
                  width: double.infinity,
                  padding: EdgeInsets.symmetric(vertical: 16.h),
                  decoration: BoxDecoration(
                    color: controller.isMeasuring.value
                        ? Colors.grey[700]
                        : const Color(0xFFBEBEBE),
                    borderRadius: BorderRadius.circular(24.r),
                  ),
                  child: Center(
                    child: controller.isMeasuring.value
                        ? Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              SizedBox(
                                width: 20.w,
                                height: 20.w,
                                child: CircularProgressIndicator(
                                  strokeWidth: 2.w,
                                  valueColor: const AlwaysStoppedAnimation<Color>(
                                      Colors.white),
                                ),
                              ),
                              SizedBox(width: 12.w),
                              Text(
                                '测量中...',
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  fontWeight: FontWeight.w500,
                                  color: Colors.white,
                                ),
                              ),
                            ],
                          )
                        : Text(
                            '开始测量',
                            style: TextStyle(
                              fontSize: 14.sp,
                              color: Colors.black,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                  ),
                ),
              )),
        ],
      ),
    );
  }

  /// 构建周/月视图柱状图
  Widget _buildWeekMonthBarChart(HeartRateAverageData? d, TimeRange timeRange) {
    // 如果没有数据，显示空图表
    if (d == null) {
      return SizedBox(
        height: 200.h,
        child: Center(
          child: Text('暂无数据',
              style: TextStyle(fontSize: 14.sp, color: Colors.grey[500])),
        ),
      );
    }

    final validData = d.automaticInfoVOS
        .where(
            (point) => (point.maxValue ?? 0) > 0 || (point.minValue ?? 0) > 0)
        .toList();

    if (validData.isEmpty) {
      return SizedBox(
        height: 200.h,
        child: Center(
          child: Text('暂无数据',
              style: TextStyle(fontSize: 14.sp, color: Colors.grey[500])),
        ),
      );
    }

    return SizedBox(
      height: 300.h,
      child: Column(
        children: [
          if (d.dateStart != null && d.dateEnd != null)
            Padding(
              padding: EdgeInsets.only(bottom: 12.h),
              child: Text('${d.dateStart} - ${d.dateEnd}',
                  style: TextStyle(fontSize: 12.sp, color: Colors.grey[400])),
            ),
          Expanded(
            child: BarChart(
              BarChartData(
                alignment: BarChartAlignment.spaceAround,
                maxY: 200,
                minY: 0,
                barTouchData: BarTouchData(
                  enabled: true,
                  touchTooltipData: BarTouchTooltipData(
                    getTooltipColor: (group) => Colors.grey[800]!,
                    getTooltipItem: (group, groupIndex, rod, rodIndex) {
                      final point = validData[group.x.toInt()];
                      return BarTooltipItem(
                        '${point.code}\n最高: ${point.maxValue}BPM\n最低: ${point.minValue}BPM',
                        TextStyle(color: Colors.white, fontSize: 11.sp),
                      );
                    },
                  ),
                ),
                titlesData: FlTitlesData(
                  show: true,
                  bottomTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      getTitlesWidget: (value, meta) {
                        final index = value.toInt();
                        if (index >= 0 && index < validData.length) {
                          final code = validData[index].code;
                          final label = timeRange == TimeRange.week
                              ? _getWeekdayLabel(code)
                              : code.split('/').last;
                          return Text(label,
                              style: TextStyle(
                                  color: Colors.grey[400], fontSize: 10.sp));
                        }
                        return const SizedBox.shrink();
                      },
                      reservedSize: 20.h,
                    ),
                  ),
                  leftTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      interval: 50,
                      getTitlesWidget: (value, meta) {
                        return Text('${value.toInt()}',
                            style: TextStyle(
                                color: Colors.grey[400], fontSize: 10.sp));
                      },
                      reservedSize: 25.w,
                    ),
                  ),
                  topTitles: const AxisTitles(
                      sideTitles: SideTitles(showTitles: false)),
                  rightTitles: const AxisTitles(
                      sideTitles: SideTitles(showTitles: false)),
                ),
                gridData: FlGridData(
                  show: true,
                  drawVerticalLine: false,
                  horizontalInterval: 50,
                  getDrawingHorizontalLine: (value) {
                    return FlLine(
                        color: Colors.grey.withOpacity(0.2), strokeWidth: 1);
                  },
                ),
                borderData: FlBorderData(show: false),
                barGroups: List.generate(validData.length, (index) {
                  final point = validData[index];
                  return BarChartGroupData(
                    x: index,
                    barRods: [
                      BarChartRodData(
                        fromY: (point.minValue ?? 0).toDouble(),
                        toY: (point.maxValue ?? 0).toDouble(),
                        color: const Color(0xFFFF8C00),
                        width: 16.w,
                        borderRadius:
                            BorderRadius.vertical(top: Radius.circular(4.r)),
                      ),
                    ],
                  );
                }),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建空的日视图图表
  Widget _buildEmptyDayChart() {
    return SizedBox(
      height: 280.h,
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: 8.w,
                height: 8.w,
                decoration: const BoxDecoration(
                  color: Color(0xFFFF8C00),
                  shape: BoxShape.circle,
                ),
              ),
              SizedBox(width: 4.w),
              Text(
                '心率数据',
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Colors.grey[400],
                ),
              ),
            ],
          ),
          SizedBox(height: 12.h),
          Expanded(
            child: Center(
              child: Text(
                '暂无数据',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.grey[500],
                ),
              ),
            ),
          ),
          SizedBox(height: 8.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: ['00:00', '06:00', '12:00', '18:00', '24:00']
                .map((label) => Text(label,
                    style: TextStyle(fontSize: 10.sp, color: Colors.grey[400])))
                .toList(),
          ),
          SizedBox(height: 16.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              Container(
                padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 12.h),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.05),
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Text('最低--BPM',
                    style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[400],
                        fontWeight: FontWeight.w500)),
              ),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 12.h),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.05),
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Text('最高--BPM',
                    style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[400],
                        fontWeight: FontWeight.w500)),
              ),
            ],
          ),
          SizedBox(height: 16.h),
          Obx(() => GestureDetector(
                onTap: controller.isMeasuring.value
                    ? null
                    : controller.startHeartRateMeasurement,
                child: Container(
                  width: double.infinity,
                  padding: EdgeInsets.symmetric(vertical: 16.h),
                  decoration: BoxDecoration(
                    color: controller.isMeasuring.value
                        ? Colors.grey[700]
                        : const Color(0xFFBEBEBE),
                    borderRadius: BorderRadius.circular(24.r),
                  ),
                  child: Center(
                    child: controller.isMeasuring.value
                        ? Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              SizedBox(
                                width: 20.w,
                                height: 20.w,
                                child: CircularProgressIndicator(
                                  strokeWidth: 2.w,
                                  valueColor: const AlwaysStoppedAnimation<Color>(
                                      Colors.white),
                                ),
                              ),
                              SizedBox(width: 12.w),
                              Text(
                                '测量中...',
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  fontWeight: FontWeight.w500,
                                  color: Colors.white,
                                ),
                              ),
                            ],
                          )
                        : Text(
                            '开始测量',
                            style: TextStyle(
                              fontSize: 14.sp,
                              color: Colors.black,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                  ),
                ),
              )),
        ],
      ),
    );
  }

  /// 获取星期标签
  String _getWeekdayLabel(String code) {
    final parts = code.split('/');
    if (parts.length == 2) {
      final month = int.tryParse(parts[0]) ?? 0;
      final day = int.tryParse(parts[1]) ?? 0;
      if (month > 0 && day > 0) {
        final date = DateTime(DateTime.now().year, month, day);
        const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
        return weekdays[date.weekday % 7];
      }
    }
    return code;
  }

  /// 构建心率区间卡片
  Widget _buildHeartRateZonesCard() {
    return _buildSectionCard(
      title: '今日运动期间心率',
      child: _buildHeartRateZones(),
    );
  }

  /// 构建心率区间
  Widget _buildHeartRateZones() {
    return Obx(() {
      final sportData = controller.sportHeartRateData.value;

      final zones = [
        {
          'name': '热身放松',
          'range': '50%-60%',
          'color': const Color(0xFFFFD700),
          'time': sportData?.warmUpRelaxTime ?? '',
          'rate': sportData?.warmUpRelaxRate ?? 0,
        },
        {
          'name': '脂肪燃烧',
          'range': '60%-70%',
          'color': const Color(0xFFFF6B35),
          'time': sportData?.fatBurningTime ?? '',
          'rate': sportData?.fatBurningRate ?? 0,
        },
        {
          'name': '心肺强化',
          'range': '70%-80%',
          'color': const Color(0xFFFF4500),
          'time': sportData?.heartLungsTime ?? '',
          'rate': sportData?.heartLungsRate ?? 0,
        },
        {
          'name': '耐力强化',
          'range': '80%-90%',
          'color': const Color(0xFFE91E63),
          'time': sportData?.enduranceReinforcementTime ?? '',
          'rate': sportData?.enduranceReinforcementRate ?? 0,
        },
        {
          'name': '无氧极限',
          'range': '90%-100%',
          'color': const Color(0xFF8B0000),
          'time': sportData?.anaerobicLimitTime ?? '',
          'rate': sportData?.anaerobicLimitRate ?? 0,
        },
      ];

      return Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            '心率区间',
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              color: Colors.white,
            ),
          ),
          SizedBox(height: 12.h),

          // 总时长
          Column(
            children: [
              Text(
                sportData?.totalDuration ?? '-- 小时 -- 分钟',
                style: TextStyle(
                  fontSize: 20.sp,
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                ),
              ),
              SizedBox(height: 4.h),
              Text(
                '总时长',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.grey[400],
                ),
              ),
            ],
          ),
          SizedBox(height: 16.h),

          // 区间分布条
          Container(
            height: 20.h,
            decoration: BoxDecoration(
              color: Colors.grey[800],
              borderRadius: BorderRadius.circular(10.r),
            ),
            child: Row(
              children: zones.map((zone) {
                final rate = zone['rate'] as int;
                return Expanded(
                  child: Container(
                    decoration: BoxDecoration(
                      color: rate > 0
                          ? (zone['color'] as Color)
                          : Colors.grey[600],
                      borderRadius: BorderRadius.circular(7.r),
                    ),
                  ),
                );
              }).toList(),
            ),
          ),
          SizedBox(height: 16.h),

          // 区间列表
          ...zones.map((zone) {
            final time = zone['time'] as String;
            final displayTime = time.isEmpty ? '-- 小时 -- 分钟' : time;

            return Padding(
              padding: EdgeInsets.only(bottom: 8.h),
              child: Row(
                children: [
                  Container(
                    width: 12.w,
                    height: 12.w,
                    decoration: BoxDecoration(
                      color: zone['color'] as Color,
                      shape: BoxShape.circle,
                    ),
                  ),
                  SizedBox(width: 8.w),
                  Expanded(
                    child: Text(
                      '${zone['name']} (${zone['range']})',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.white,
                      ),
                    ),
                  ),
                  Text(
                    displayTime,
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.grey[400],
                    ),
                  ),
                ],
              ),
            );
          }),
        ],
      );
    });
  }

  /// 构建今日平均睡眠心率卡片
  Widget _buildAverageSleepHeartRateCard() {
    return _buildSectionCard(
      title: '今日平均睡眠心率',
      child: _buildAverageSleepHeartRate(),
    );
  }

  /// 构建今日平均睡眠心率
  Widget _buildAverageSleepHeartRate() {
    return Obx(() {
      final sleepData = controller.sleepHeartRateData.value;

      final averageHeartRate = sleepData?.average ?? 0;
      final lowestHeartRate = sleepData?.minHeartRate ?? 0;
      final fluctuationRange = sleepData?.fluctuationRange ?? 0;

      return Column(
        children: [
          // 时间范围（暂时使用固定值，可以从其他API获取）
          Text(
            '23:56-08:30',
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.grey[400],
            ),
          ),
          SizedBox(height: 16.h),

          // 三个指标
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildSleepHeartRateMetric(
                  '平均心率',
                  averageHeartRate,
                  sleepData?.averageInfo ?? '--',
                  sleepData?.isAverageNormal ?? false),
              _buildSleepHeartRateMetric(
                  '最低心率',
                  lowestHeartRate,
                  sleepData?.minHeartRateInfo ?? '--',
                  sleepData?.isMinHeartRateNormal ?? false),
              _buildSleepHeartRateMetric(
                  '波动幅度',
                  fluctuationRange,
                  sleepData?.fluctuationRangeInfo ?? '--',
                  sleepData?.isFluctuationNormal ?? false),
            ],
          ),
          SizedBox(height: 16.h),

          // 趋势说明
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildTrendIndicator(
                  '比昨天',
                  sleepData != null && sleepData.averageValue != 0
                      ? '${sleepData.averageValue.abs()}bpm'
                      : '--',
                  sleepData != null && sleepData.averageValue > 0),
              _buildTrendIndicator(
                  '比昨天',
                  sleepData != null && sleepData.minHeartRateValue != 0
                      ? '${sleepData.minHeartRateValue.abs()}bpm'
                      : '--',
                  sleepData != null && sleepData.minHeartRateValue > 0),
              _buildTrendIndicator(
                  '比昨天',
                  sleepData != null && sleepData.fluctuationRangeValue != 0
                      ? '${sleepData.fluctuationRangeValue.abs()}bpm'
                      : '--',
                  sleepData != null && sleepData.fluctuationRangeValue > 0),
            ],
          ),
        ],
      );
    });
  }

  /// 构建睡眠心率指标
  Widget _buildSleepHeartRateMetric(
      String title, int value, String status, bool isNormal) {
    return Column(
      children: [
        Text(
          title,
          style: TextStyle(
            fontSize: 12.sp,
            color: Colors.grey[400],
          ),
        ),
        SizedBox(height: 8.h),
        Text(
          '$value',
          style: TextStyle(
            fontSize: 24.sp,
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
        ),
        Text(
          'BPM',
          style: TextStyle(
            fontSize: 12.sp,
            color: Colors.grey[400],
          ),
        ),
        SizedBox(height: 4.h),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 2.h),
          decoration: BoxDecoration(
            color: isNormal
                ? const Color(0xFF00C08B).withOpacity(0.2)
                : const Color(0xFFFF6B35).withOpacity(0.2),
            borderRadius: BorderRadius.circular(8.r),
          ),
          child: Text(
            status,
            style: TextStyle(
              fontSize: 10.sp,
              color:
                  isNormal ? const Color(0xFF00C08B) : const Color(0xFFFF6B35),
            ),
          ),
        ),
      ],
    );
  }

  /// 构建趋势指示器
  Widget _buildTrendIndicator(String label, String value, bool isUp) {
    return Column(
      children: [
        Text(
          label,
          style: TextStyle(
            fontSize: 10.sp,
            color: Colors.grey[500],
          ),
        ),
        SizedBox(height: 2.h),
        Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              isUp ? Icons.arrow_upward : Icons.arrow_downward,
              size: 12.sp,
              color: Colors.grey[400],
            ),
            Text(
              value,
              style: TextStyle(
                fontSize: 10.sp,
                color: Colors.grey[400],
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建心率信息说明卡片
  Widget _buildHeartRateInfoCard() {
    return _buildSectionCard(
      title: '关于心率数据',
      child: _buildHeartRateInfo(),
    );
  }

  /// 构建心率信息说明
  Widget _buildHeartRateInfo() {
    return RichText(
      text: TextSpan(
        style: TextStyle(
          fontSize: 13.sp,
          color: Colors.green[100],
          height: 1.5,
        ),
        children: [
          TextSpan(
            text: '静息心率：',
            style: TextStyle(
              fontWeight: FontWeight.w500,
              color: Colors.white,
            ),
          ),
          const TextSpan(
            text: '正常人在安静状态下每分钟心跳次数一般为 60 - 100次。\n\n',
          ),
          TextSpan(
            text: '运动心率：',
            style: TextStyle(
              fontWeight: FontWeight.w500,
              color: Colors.white,
            ),
          ),
          const TextSpan(
            text: '运动过程中根据心率区间可以判断身体的运动状态，选择合适的心率区间才能达到较佳的运动效果。',
          ),
        ],
      ),
    );
  }

  /// 通用分区卡片（参考睡眠页面样式）
  Widget _buildSectionCard({
    required String title,
    required Widget child,
    VoidCallback? onHelpTap,
  }) {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0xff282528),
        borderRadius: BorderRadius.circular(20.r),
        border: Border.all(
          color: const Color.fromRGBO(33, 33, 33, 1),
          width: 1,
        ),
      ),
      child: Column(
        children: [
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.h),
            child: Row(
              children: [
                Text(
                  title,
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                    color: Colors.white,
                  ),
                ),
                const Spacer(),
                if (onHelpTap != null)
                  GestureDetector(
                    onTap: onHelpTap,
                    child: Icon(
                      Icons.help_outline,
                      color: Colors.white.withOpacity(0.9),
                      size: 18.sp,
                    ),
                  ),
              ],
            ),
          ),
          const Divider(
            height: 1,
            thickness: 1,
            color: Color(0xff353235),
          ),
          Padding(
            padding: EdgeInsets.all(12.w),
            child: child,
          ),
        ],
      ),
    );
  }

  /// 构建手动测量记录卡片（独立卡片，不在图表内）
  Widget _buildManualMeasurementRecordsCard() {
    return Obx(() {
      final heartRateAverageData = controller.heartRateAverageData.value;
      if (heartRateAverageData == null || heartRateAverageData.manualInfoVOS.isEmpty) {
        return const SizedBox.shrink();
      }

      // 使用本地状态管理折叠状态
      final isExpanded = false.obs;

      return _buildSectionCard(
        title: '当天测量记录 (${heartRateAverageData.manualInfoVOS.length})',
        child: Obx(() => Column(
          children: [
            GestureDetector(
              onTap: () => isExpanded.value = !isExpanded.value,
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 8.h),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      isExpanded.value ? '收起' : '展开查看',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[400],
                      ),
                    ),
                    SizedBox(width: 4.w),
                    Icon(
                      isExpanded.value ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                      color: Colors.grey[400],
                      size: 20.sp,
                    ),
                  ],
                ),
              ),
            ),
            if (isExpanded.value) ...[
              SizedBox(height: 8.h),
              ConstrainedBox(
                constraints: BoxConstraints(maxHeight: 200.h),
                child: SingleChildScrollView(
                  child: Column(
                    children: heartRateAverageData.manualInfoVOS.map((record) {
                      return Container(
                        margin: EdgeInsets.only(bottom: 8.h),
                        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.h),
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.05),
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              record.code,
                              style: TextStyle(
                                fontSize: 13.sp,
                                color: Colors.grey[300],
                              ),
                            ),
                            Text(
                              '${record.value} BPM',
                              style: TextStyle(
                                fontSize: 13.sp,
                                color: Colors.white,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                      );
                    }).toList(),
                  ),
                ),
              ),
            ],
          ],
        )),
      );
    });
  }
}
